package org.spdata.tsdb.dao;

import java.util.Arrays;

import javax.annotation.PreDestroy;

import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;


public class MongoHelper {
	private MongoClient client = null;
	private String host;
	private int port;
	private String userName;
	private String password;
	private String dbName;
	private MongoDatabase database = null;
	
	
	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getDbName() {
		return dbName;
	}

	public void setDbName(String dbName) {
		this.dbName = dbName;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	private MongoClientOptions getConfOptions() {
		return new MongoClientOptions.Builder()
				.socketKeepAlive(true)
				.connectTimeout(5000)
				.socketTimeout(50000)
				.writeConcern(WriteConcern.ACKNOWLEDGED)
				.build();
	}
	
	public MongoClient getClient(){
		if(client==null){
			if(this.userName!=null && this.userName.isEmpty()==false){
				MongoCredential credential = MongoCredential.createCredential(
						userName, dbName, password.toCharArray());  
				client = new MongoClient(new ServerAddress(host, port),
						Arrays.asList(credential),getConfOptions());
			}else{
				client = new MongoClient(new ServerAddress(host, port),
						getConfOptions());
			}
		}
		return client;
	}
	
	public MongoDatabase getDatabase(){
		if(database==null){
			MongoClient c = this.getClient();
			database = c.getDatabase(dbName);
		}
		return database;
	}
	
	public MongoCollection<Document> getCollection(String collectionName){
		return this.getDatabase().getCollection(collectionName);
	}
	
	@PreDestroy  
	public void destory(){
		if(this.client!=null ){
			this.client.close();
		}
	}
}
